<template>
  <view class="container" style="background: #fff; padding-top: 5px">
    <uni-section title="基础数据" type="line">
      <view class="example" style="padding: 10px">
        <uni-forms ref="baseForm" :model="formData" labelWidth="180rpx">
          <uni-forms-item label="车牌号码" name="licensePlate" :required="true">
            <uni-easyinput
              type="text"
              v-model="formData.licensePlate"
              placeholder="请输入车牌号"
              :disabled="formData.status != 0"
              required
            />
          </uni-forms-item>
          <uni-forms-item label="联系电话" name="contactNumber">
            <uni-easyinput
              type="text"
              v-model="formData.contactNumber"
              placeholder="请输入联系电话"
              :disabled="formData.status != 0"
              required
            />
          </uni-forms-item>
          <uni-forms-item label="选择门店" :required="true">
            <uni-data-select
              v-model="formData.storeId"
              :localdata="selectData.storeList"
              required
              :disabled="true"
            >
            </uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="选择仓库" :required="true">
            <uni-data-select
              v-model="formData.warehouseId"
              :localdata="selectData.warehouseList"
              required
              :disabled="formData.status != 0"
            >
            </uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="存储类型" :required="true">
            <uni-data-select
              v-model="formData.storageType"
              :localdata="selectData.storageTypeList"
              :disabled="formData.status != 0"
              required
            >
            </uni-data-select>
          </uni-forms-item>
        </uni-forms>
      </view>
    </uni-section>

    <uni-section title="轮胎数据" type="line">
      <view class="button-sp-area">
        <button
          class="mini-btn"
          type="warn"
          size="mini"
          @click="delDepositRecordsDetail"
          :disabled="formData.status != 0"
          >删除
        </button>
        <button
          class="mini-btn"
          type="primary"
          size="mini"
          @click="addDepositRecordsDetail"
          :disabled="formData.status != 0"
          >新增
        </button>
      </view>
      <uni-table
        ref="table"
        :loading="loading"
        border
        stripe
        type="selection"
        emptyText="暂无更多数据"
        @selection-change="selectionChange"
      >
        <uni-tr>
          <uni-th width="150" align="center">季节胎型</uni-th>
          <uni-th width="150" align="center">轮胎品牌</uni-th>
          <uni-th width="150" align="center">轮胎型号</uni-th>
          <uni-th align="center">存储数量</uni-th>
          <uni-th align="center">备注</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in formData.depositRecordsDetails" :key="index">
          <uni-td align="center">
            <uni-data-select
              :disabled="formData.status != 0"
              v-model="item.tireSeason"
              :localdata="selectData.tireSeasonList"
            ></uni-data-select>
          </uni-td>
          <uni-td align="center">
            <next-data-select :disabled="formData.status != 0" :filterable="true" :options="selectData.tireBrandList" v-model="item.tireBrand" />
          </uni-td>
          <uni-td align="center">
            <next-data-select :disabled="formData.status != 0" :filterable="true" :options="selectData.tireModelList" v-model="item.tireModel" />
          </uni-td>
          <uni-td align="center">
            <uni-number-box
              :min="1"
              v-model="item.storageQuantity"
              :disabled="formData.status != 0"
            />
          </uni-td>
          <uni-td align="center">
            <uni-easyinput
              v-model="item.notes"
              :disabled="formData.status != 0"
            />
          </uni-td>
        </uni-tr>
        <view style="width: 100%; height: 200px">&nbsp;</view>
      </uni-table>
    </uni-section>
    <view style="width: 100%; height: 80px">&nbsp;</view>

    <view
      class="goods-carts"
      v-show="['0', '1'].includes(`${formData.status}`)"
      style="z-index: 9999"
    >
      <uni-goods-nav
        v-if="!!uniGgoodsNavData[`status${formData.status}`]"
        :fill="true"
        :options="{}"
        :button-group="uniGgoodsNavData[`status${formData.status}`].buttonGroup"
        @buttonClick="submitForm"
      />
    </view>

    <view
      class="goods-carts"
      v-show="['0', '1', '5', '7'].includes(`${formData.status}`)"
      style="z-index: 9999"
    >
      <uni-goods-nav
        v-if="!!uniGgoodsNavData[`status${formData.status}`]"
        :fill="true"
        :options="{}"
        :button-group="uniGgoodsNavData[`status${formData.status}`].buttonGroup"
        @buttonClick="submitForm"
      />
    </view>
  </view>
</template>

<script lang="ts">
  import { DictUtils } from '@/sheep/store/DictUtils';
  import { StoreApi } from '@/sheep/api/store';
  import { WarehouseApi } from '@/sheep/api/warehouse';
  import { DepositRecordsApi } from '@/sheep/api/depositrecords';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';

  export default {
    components: { UniEasyinput },
    onLoad(options) {
      this.id = options.id; // 获取 URL 中传递的 id 参数
      this.type = options.type; // 获取 URL 中传递的 id 参数
    },
    mounted() {
      this.initSelectData();
      this.query();
    },
    data() {
      return {
        id: undefined,
        type: undefined, //edit、add
        selectData: {
          storeList: [],
          storageTypeList: [],
          warehouseList: [],
          tireSeasonList: [],
          tireBrandList: [],
          tireModelList: [],
        },
        formData: {
          id: undefined,
          storeId: undefined,
          licensePlate: '吉A',
          contactNumber: undefined,
          startDate: undefined,
          storageDays: 9,
          expirationDate: undefined,
          storageType: '0',
          warehouseId: undefined,
          warehouseDetail: undefined,
          notes: undefined,
          status: 0,
          depositRecordsDetails: [],
        },
        loading: false,
        options: [],
        uniGgoodsNavData: {
          status0: {
            buttonGroup: [
              {
                text: '保存',
                backgroundColor: '#2ea1f4',
                color: '#fff',
              },
              {
                text: '立即预约',
                backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
                color: '#fff',
              },
            ],
          },
          status1: {
            buttonGroup: [
              {
                text: '取消预约',
                backgroundColor: '#919191',
                color: '#fff',
              },
            ],
          },
          // status4:{
          //   buttonGroup: [
          //     {
          //       text: '新增存胎单',
          //       backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
          //       color: '#fff',
          //     },
          //   ],
          // },
          status5: {
            buttonGroup: [
              {
                text: '新增存胎单',
                backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
                color: '#fff',
              },
            ],
          },
          status7: {
            buttonGroup: [
              {
                text: '新增存胎单',
                backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
                color: '#fff',
              },
            ],
          },
        },
      };
    },
    methods: {
      async submitForm(e) {
        if (this.formData.status === 0) {
          // 更新库存数量
          this.formData.depositRecordsDetails.forEach((item) => {
            item.remainingQuantity = item.storageQuantity;
          });
        }
        // 如果操作不是 "保存"，则更新状态
        if (e.content.text === '取消预约') {
          const { code, msg } = await DepositRecordsApi.deleteDepositRecords(this.formData.id);
          uni.showToast({
            title: code == '0' ? '删除成功' : msg,
            icon: 'none',
          });
          uni.navigateBack();
          return;
        } else if (e.content.text === '新增存胎单') {
          uni.navigateTo({
            url: `/pages/depositrecords/components/CopyAndGenerateDepositById?id=${this.formData.id}`,
          });
          return;
        } else if (e.content.text !== '保存') {
          const statusMap = { 0: 1, 1: 2, 3: 4 };
          this.formData.status = statusMap[this.formData.status] || this.formData.status;
        }

        // 选择 API 方法
        const apiMethod = this.formData.id
          ? DepositRecordsApi.updateDepositRecords
          : DepositRecordsApi.createDepositRecords;

        try {
          if (!this.formData.id) {
            this.calculateDate(); // 仅创建时计算日期
          }

          const { code, msg } = await apiMethod(this.formData);

          this.showToast(code == '0' ? '提交成功' : msg);

          if (code == '0') {
            uni.navigateBack();
          }
        } catch (error) {
          this.showToast('请求失败，请稍后重试');
          console.error('提交表单失败:', error);
          uni.navigateBack();
        }
      },
      // 统一封装 Toast 提示
      showToast(message) {
        uni.showToast({
          title: message,
          icon: 'none',
        });
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index;
      },
      addDepositRecordsDetail() {
        this.formData.depositRecordsDetails.push({
          tireSeason:
            this.selectData.tireSeasonList.length !== 0
              ? this.selectData.tireSeasonList[0].value
              : '',
          tireBrand:
            this.selectData.tireBrandList.length !== 0
              ? this.selectData.tireBrandList[0].value
              : '',
          tireModel:
            this.selectData.tireModelList.length !== 0
              ? this.selectData.tireModelList[0].value
              : '',
          notes:'',
          storageQuantity: 4,
        });
      },
      delDepositRecordsDetail() {
        if (this.selectedIndexs && this.selectedIndexs.length > 0) {
          // 逆序删除，避免下标错乱
          this.selectedIndexs
            .sort((a, b) => b - a)
            .forEach((index) => {
              this.formData.depositRecordsDetails.splice(index, 1); // 删除对应下标的对象元素
            });
        }
      },
      async initSelectData() {
        try {
          // 获取字典数据
          const dictDataPromises = [
            DictUtils.getDictData('tire_storage_type'),
            DictUtils.getDictData('tire_storage_season'),
            DictUtils.getDictData('tire_storage_brand'),
            DictUtils.getDictData('tire_storage_model'),
          ];
          const [storageTypeList, tireSeasonList, tireBrandList, tireModelList] = await Promise.all(
            dictDataPromises,
          );
          this.selectData.storageTypeList = storageTypeList;
          this.selectData.tireSeasonList = tireSeasonList;
          this.selectData.tireModelList = tireModelList;
          this.selectData.tireBrandList = tireBrandList;

          // 获取仓库和商店数据
          const storeResultPromise = StoreApi.getStorePage({});
          const warehouseResultPromise = WarehouseApi.getWarehousePage({});

          const [storeResult, warehouseResult] = await Promise.all([
            storeResultPromise,
            warehouseResultPromise,
          ]);

          this.selectData.storeList = await this.buildSelectData(
            storeResult?.data?.list || [],
            'storeName',
          );
          this.selectData.warehouseList = await this.buildSelectData(
            warehouseResult?.data?.list || [],
            'warehouseName',
          );

          //新增的情况下、并且 仓库列表有值
          if (!this.id) {
            //初始化详情
            await this.addDepositRecordsDetail();
            if (this.selectData?.warehouseList?.length) {
              this.formData.warehouseId = this.selectData.warehouseList[0].value;
            }
            this.formData.storeId = uni.getStorageSync('storeId');
          }
        } catch (error) {
          console.error('初始化选择数据时出错:', error);
          // 可以在这里添加一些用户友好的提示或错误处理逻辑
        }
      },
      async query() {
        if (!this.id) {
          return;
        }
        const { data: depositRecordsData } = await DepositRecordsApi.getDepositRecords(this.id);
        this.formData = depositRecordsData || {};

        const { data: depositRecordsDetailData } =
          await DepositRecordsApi.getDepositRecordsDetailListByTireDepositRecordsId(this.id);
        this.formData.depositRecordsDetails = depositRecordsDetailData || [];
      },
      async buildSelectData(list: any[], name: string) {
        return list.map((item) => ({
          value: item['id'],
          text: item[name],
        }));
      },
      // 格式化时间
      formatDate(date: string) {
        const d = new Date(date);
        const pad = (num: number) => String(num).padStart(2, '0');

        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(
          d.getHours(),
        )}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      },
      calculateDate() {
        const now = new Date();
		    this.formData.startDate = now.getTime()
        const targetMonth = now.getMonth() + parseInt(this.formData.storageDays);

        // 先设置目标月的1号，确保不会溢出
        const targetDate = new Date(now);
        targetDate.setMonth(targetMonth, 1);

        // 计算目标月的最大天数
        const lastDayOfMonth = new Date(
          targetDate.getFullYear(),
          targetDate.getMonth() + 1,
          0,
        ).getDate();

        // 目标日期 = min(原日期, 目标月最后一天)
        targetDate.setDate(Math.min(now.getDate(), lastDayOfMonth));

        // 更新表单中的 expirationDate
        this.formData.expirationDate = new Date(targetDate).getTime();

        return this.formData.expirationDate;
      },
    },
  };
</script>

<style>
  .mini-btn {
    margin-left: 10rpx;
  }

  .example-body {
    padding: 0;
    /* #ifndef APP-NVUE */
    display: block;
    /* #endif */
  }

  .goods-carts {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    position: fixed;
    left: 0;
    right: 0;
    /* #ifdef H5 */
    left: var(--window-left);
    right: var(--window-right);
    /* #endif */
    bottom: 0;
  }
</style>
